<?php
/* --------------------------------------------------------------
  dependent.inc.php 2023-01-30
  Gambio GmbH
  http://www.gambio.de
  Copyright (c) 2023 Gambio GmbH
  Released under the GNU General Public License (Version 2)
  [http://www.gnu.org/licenses/gpl-2.0.html]
  --------------------------------------------------------------*/

declare(strict_types=1);

$logfiles = array_merge(glob(DIR_FS_CATALOG . 'logfiles/*.log.json'), glob(DIR_FS_CATALOG . 'logfiles/*.log.txt'));

foreach ($logfiles as $logfile) {
    $currentLogfile = fopen($logfile, 'r+');
    if ($currentLogfile !== false && flock($currentLogfile, LOCK_EX | LOCK_NB, $wouldBlock) === true
        && !$wouldBlock) {
        $currentLogfileContent = file_get_contents($logfile);
        ftruncate($currentLogfile, 0);
        fclose($currentLogfile);
        
        $zippedLogfileContent = gzencode($currentLogfileContent, 9);
        $zippedLogfilePath    = $logfile . '.' . date('Y-m-d_H-i-s') . '.gz';
        $zippedLogfile        = fopen($zippedLogfilePath, 'w+');
        fwrite($zippedLogfile, $zippedLogfileContent);
        fclose($zippedLogfile);
    }
}
